import React, { Component } from 'react';
import { render, unmountComponentAtNode } from 'react-dom';
import _ from 'underscore';

export default class SideSlider extends Component {
  static mount(props = {}, parent = document.body) {
    let container = document.createElement('div');
    $(container).css({
      position: 'absolute',
      left: '0px',
      top: '0px',
      width: '100%',
      height: '100%',
      zIndex: 1000
    }).appendTo(parent);

    let parameters = _.defaults({}, props, this.defaultProps);
    return render(<this {...parameters} />, container, function () {
      this.__container = container;
    });
  } // mount

  static unMount(dialog) {
    let container = dialog.__container;
    if (container) {
      unmountComponentAtNode(container);
      $(container).remove();

      if (dialog) {
        dialog.__container = null;
      }
    }
  } // unMount

  close(args) {
    $(this.refs.content).animate({
      right: `-${ this.props.width }px`
    }, 300, () => {
      SideSlider.unMount(this);

      if (this.props.onClosed) {
        this.props.onClosed(args.constructor.name !== 'SyntheticMouseEvent' ? args : null);
      }
    });
  } // close

  componentDidMount() {
    $(this.refs.content).animate({
      right: '0px'
    }, 300);

    $(document.body).css({
      overflowY: 'hidden'
    })
  } // componentDidMount

  componentWillUnmount() {
    $(document.body).css({
      overflowY: ''
    });
  } // componentWillUnmount

  renderBody() {
    return (
      <div>需要重写 renderBody 方法。</div>
    );
  } // renderBody

  render() {
    return (
      <div className="slider-container">
        <div ref="content" className="content-container" style={{
          width: this.props.width,
          right: -1 * this.props.width
        }}>
          { this.renderBody() }
        </div>
        <div className="dialog-backdrop" onClick={ this.close.bind(this) }></div>
      </div>
    );
  } // render
}

SideSlider.defaultProps = {
  width: 365,
  onClosed: null
}
